package com.doyens.reggie.controller;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doyens.reggie.commons.R;
import com.doyens.reggie.domain.Category;
import com.doyens.reggie.domain.Dish;
import com.doyens.reggie.domain.DishFlavor;
import com.doyens.reggie.dto.DishDto;
import com.doyens.reggie.service.CategoryService;
import com.doyens.reggie.service.DishFlavorService;
import com.doyens.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;

    // 根据分类的id【菜系】查询菜品
    @GetMapping("/list")
    public R<List> findByCategory(long categoryId){
        List<DishDto> dishDtoList=null;
         String key="dish_"+categoryId;
         dishDtoList=(List<DishDto>) redisTemplate.opsForValue().get(key);
         if(dishDtoList!=null){
             return R.success(dishDtoList);
         }
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId,categoryId);
        wrapper.eq(Dish::getStatus,1);
        List<Dish> list = dishService.list(wrapper);
        dishDtoList= list.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            LambdaQueryWrapper<DishFlavor> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> list1 = dishFlavorService.list(wrapper1);
            dishDto.setFlavors(list1);
            return dishDto;
        }).collect(Collectors.toList());
          redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }

    // 完成修改功能
    @PutMapping
    public R<String> updateDish(@RequestBody DishDto dishDto){
        dishService.updateDish(dishDto);
        String key="dish_"+dishDto.getCategoryId();
           redisTemplate.delete(key);
        return R.success("修改成功");
    }

    // 根据id查询菜品 做回显
    @GetMapping("/{id}")
    public R<DishDto> findDishById(@PathVariable long id){
        Dish dish = dishService.getById(id);//8 少3个
        DishDto dishDto = new DishDto(); //11 null
        BeanUtils.copyProperties(dish,dishDto);//{8,null,null,null}补齐口味

        // 查询菜品的口味
        List<DishFlavor> list = dishFlavorService.list(new LambdaQueryWrapper<DishFlavor>().eq(DishFlavor::getDishId, id));
        dishDto.setFlavors(list);
        return R.success(dishDto);
    }

    // 停售和起售
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable int status,Long[] ids){

        dishService.updateStatus(status,ids);

        return R.success(status == 1?"启售成功":"停售成功");
    }

    // 删除和批量删除
    @DeleteMapping
    public R<String> delDish(Long[] ids){
        dishService.delDishAndFlavor(ids);
        return R.success("删除成功");
    }

    // 分页带搜索的查询
    @GetMapping("/page")
    public R<IPage> page(int page,int pageSize,@RequestParam(name = "name",required = false) String name){
        Page<Dish> params = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!StringUtils.isEmpty(name), Dish::getName,name);
        Page<Dish> pb = dishService.page(params, wrapper);

        //pb{total:24,records:[{Dish(不能封装菜系名称，categoryId=1)},{Dish categoryId=1}]}
        //pbDto{total:24,records:[{DishDto(湘菜)},{DishDto(川菜)}]}

        Page<DishDto> pbDto = new Page<>();//{total=0  records=null}
        pbDto.setTotal(pb.getTotal());
        ArrayList<DishDto> dishDtos = new ArrayList<>();
        List<Dish> records = pb.getRecords();
        for (Dish dish : records) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);//对象的赋值  少一个categoryName  categoryId--->category--->name
            Category category = categoryService.getById(dish.getCategoryId());
            if(category != null){
                dishDto.setCategoryName(category.getName());
            }
           dishDtos.add(dishDto);
        }
        pbDto.setRecords(dishDtos);

        return R.success(pbDto);
    }

    //添加菜品
    @PostMapping
    public R<String> saveDish(@RequestBody DishDto dishDto){
        log.info("菜品：" + dishDto);
//        删除Redis中的数据，只删除对应的分类数据
          String key="dish_"+dishDto.getCategoryId();
          redisTemplate.delete(key);
        dishService.saveDishAndFlavor(dishDto);
        return R.success("添加成功");
    }

}
